const { ipcRenderer } = require("electron");
const { storage, pendantStorage } = require("./common/utils/storage.js");
const { setStorage,getStorage, getItemStorage, deleteItemStorage } = pendantStorage()
let wins = [];
let lockingNativeWin = ['./folderPendant/']


const getBounds = (x, y) => { 
  let displayMatching = utools.getDisplayNearestPoint({x,y});
  let display = utools.getPrimaryDisplay();
  let displayMatchingScaleFactor =  displayMatching.scaleFactor;
  let displayScaleFactor =  display.scaleFactor;

  let difference = displayScaleFactor - displayMatchingScaleFactor;
  return function (width, height){
    if(difference > 0){
      width = parseInt(width * (1 + difference));
      height = parseInt(height * (1 + difference));
      return {
        x, y, width, height
      }
    }else if(difference < 0){
      width = parseInt(width / (1 - difference));
      height = parseInt(height / (1 - difference));
      return {
        x, y, width, height
      }
    }else{
      return {
        x,
        y,
        width,
        height
      }
    }
  }
}

window.createWinChild = async (option) => {
  let obj;
  const currentNativeId = utools.getNativeId();
  if(option.x && option.y){
   obj = getBounds(option.x,option.y)(option.width, option.height);
  }
  let { x, y, width, height, size, alwaysOnTop, nanoid, url, minHeight, minWidth ,display, nativeId, lockingNative} = {...option, ...obj};
  if(lockingNative && currentNativeId !== nativeId)return;
  const data = getStorage(nanoid);
  return new Promise((resolve, reject) => {
    setTimeout(()=>{
      const ubWindow = utools.createBrowserWindow(
        option.url + "index.html",
        {
          title: "Pendant",
          frame: false,
          backgroundColor: "rgba(255,255,255,0)",
          transparent: true,
          titleBarStyle: "hidden",
          resizable: option.resizable === false ? false : true,
          width: option.width || parseInt(size.width * 100),
          height: option.height || parseInt(size.height * 100),
          minWidth,
          minHeight,
          x: x || 50,
          y: y || 50,
          webPreferences: {
            preload: option.url + "preload.js",
            spellcheck: false,
          },
        },
        () => {
          if(option.x && option.y){
            let resetWidth = option.width || size.width * 100;
            let resetHeight = option.height || size.height * 100;
            ubWindow.setBounds({x: option.x, y: option.y, width: resetWidth, height: resetHeight})
          }
          ubWindow.setBackgroundColor("rgba(255,255,255,0)");
          ubWindow.show();
          ubWindow.setSkipTaskbar(true);
          ubWindow.setAlwaysOnTop(alwaysOnTop, 'pop-up-menu');
          // ubWindow.webContents.openDevTools();
          ubWindow.nanoid = nanoid;
          ubWindow.nativeId = currentNativeId;
          ubWindow.url = url;
          ipcRenderer.sendTo(ubWindow.webContents.id, "senderId");
          ipcRenderer.sendTo(ubWindow.webContents.id, "init", data);
  
          wins.push(ubWindow);
          resolve(ubWindow);
        }
      );
  
    })
  });
}

const winItem = (event) => {
  return wins.find((item) => item.webContents.id === event.senderId);
};

const closeWinItem = (event) => {
  let index = wins.findIndex(item=>{
    if(item.webContents.id === event.senderId){
      return true
    }
  })
  if(index !== -1){
    wins.splice(index, 1)
  }
}

ipcRenderer.on("win", (event, type) => {
  let win = winItem(event);
  switch (type) {
    case "close": {
      storage.delete(win.nanoid);
      deleteItemStorage(win.url, win.nanoid);
      win.moveTop();
      closeWinItem(event);
      win.destroy();
      break;
    }
    case "alwaysOnTop": {
      let bool = win.isAlwaysOnTop();
      console.log(bool);
      win.setAlwaysOnTop(!bool, 'pop-up-menu');
      bool = win.isAlwaysOnTop();
      event.sender.sendTo(event.senderId, "isAlwaysOnTop", bool);
      break;
    }
    case "isAlwaysOnTop": {
      let bool = win.isAlwaysOnTop();
      event.sender.sendTo(event.senderId, "isAlwaysOnTop", bool);
      break;
    }
    case "position": {
      let [x, y] = win.getPosition();
      let [width, height] = win.getSize();
      event.sender.sendTo(event.senderId, "position", {
        data: { x, y, width, height },
        url: win.url
      });
      break;
    }
    default:
      break;
  }
});

ipcRenderer.on("getBounds", (event, data)=>{
  let win = winItem(event);
  let bounds = win.getBounds();
  event.sender.sendTo(event.senderId, "getBounds", bounds);
})

ipcRenderer.on("setSize", (event, data) => {
  let win = winItem(event);
  let { width, height } = data;
  win.setSize(width, height);
});

ipcRenderer.on("setResizable", (event, bool) => {
  let win = winItem(event);
  win.setResizable(bool);
});

ipcRenderer.on("setPosition", (event, data) => {
  let win = winItem(event);
  
  win.setBounds(data);
});

ipcRenderer.on("direction", (event, data) => {
  let win = winItem(event);
  let {x, y, width, height} = win.getBounds();
  let {type, num} = data
  if(type === 'left'){
    x = x - num
  } else if (type === 'top') {
    y = y - num
  } else if (type === 'right') {
    x = x + num
  } else if (type === 'bottom') {
    y = y + num
  }
  win.setBounds({
    x,y,width, height
  });
});

ipcRenderer.on("saveData", (event, data) => {

  let win = winItem(event);
  let nanoid = win.nanoid;
  let nativeId = win.nativeId
  let alwaysOnTop = win.isAlwaysOnTop();
  let [x, y] = win.getPosition();
  let [width, height] = win.getSize();
  let url = win.url;
  let minWidth = "";
  let minHeight = "";
  let lockingNative = false;
  
  lockingNativeWin.forEach(item=>{
    if(item === url){
      lockingNative = true
    }else{
      lockingNative = false
    }
  })

  if (url == "./folderPendant/" && data) {
    minWidth = data.iconSize + data.spacing * 2;
    minHeight = data.iconSize + data.spacing * 2;
    win.setMinimumSize(minWidth, minHeight);
    if(minWidth > width || minHeight > height){ win.setSize(minWidth, minHeight) }
  }
  setStorage({ url, nanoid, data })
  storage.put({
    nanoid,
    nativeId,
    lockingNative,
    alwaysOnTop,
    x,
    y,
    width: width,
    height: height,
    url,
    minWidth,
    minHeight,
  });
});
